package inet.app.vod.activity.common;

import inet.app.vod.MyApp;
import inet.app.vod.activity.R;
import inet.app.vod.activity.account.AccountInfoActivity;
import inet.app.vod.activity.account.LoginActivity;
import inet.app.vod.activity.account.RegisterActivity;
import inet.app.vod.activity.film.IPhimActivity;
import inet.app.vod.activity.search.SearchActivity;
import inet.app.vod.config.AppConstants;
import inet.app.vod.object.MenuUIItem;
import inet.app.vod.object.User;
import inet.app.vod.util.MyPreferenceManager;
import inet.app.vod.util.MyUtil;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.facebook.Response;
import com.inet.app.framework.bitmap.UniversalImageUtil;
import com.inet.app.framework.intentutil.LaunchIntent;
import com.inet.app.framework.social.facebook.FacebookRequestStatus;
import com.inet.app.framework.social.facebook.FacebookUtil;
import com.inet.app.framework.util.Log;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.nostra13.universalimageloader.core.assist.PauseOnScrollListener;

public abstract class BaseActivity extends FragmentActivity {

	public PauseOnScrollListener mScrollingListener;

	protected ArrayList<MenuUIItem> mMenuItems = new ArrayList<MenuUIItem>();
	protected Context mContext;
	protected SlidingMenu mSlideMenu;
	protected ProgressDialog dialogLoading;
	protected MyApp mApplication;

	protected FragmentManager mFragmentManager;
	protected MenuListFragment mMenuFragment;
	protected int mTagMenu;
	protected FacebookUtil mFacebook;

	private AlertDialog mShareDialog;
	private View mLoadingLayout;
	private ImageView mMenuView;
	private ImageView mAccountView;
	private TextView mTitle;
	private Dialog mDialogAcc;
	private boolean isRunning = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		initModelBase(savedInstanceState);
		mFacebook = FacebookUtil.newInstance(this);
		mFacebook.onCreate(savedInstanceState);
	}

	@Override
	public void onStart() {
		super.onStart();
		mFacebook.onStart();
		isRunning = true;
	}

	@Override
	public void onResume() {
		super.onResume();
		setTagMenu();
		// update account status
		checkStatusAccount();

		// update menu for current activity
		for (MenuUIItem item : mMenuItems) {
			item.setSelect(false);
		}
		if (mTagMenu >= 0 && mTagMenu < mMenuItems.size()) {
			mMenuItems.get(mTagMenu).setSelect(true);
			mMenuFragment.notifyDataSetChanged(mMenuItems);
		}
	}

	@Override
	public void onStop() {
		super.onStop();
		mFacebook.onStop();
		isRunning = false;
		Log.d(this.getClass().getSimpleName() + " stop");
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mFacebook.onSaveInstanceState(outState);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		mFacebook.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * Current menu
	 */
	public abstract void setTagMenu();

	/**
	 * Check account login/logout
	 */
	private void checkStatusAccount() {
		if (isLogin()) {
			if (mAccountView != null) {
				mAccountView.setImageResource(R.drawable.ico_account_logined);
			}
		}

		else {
			if (mAccountView != null) {
				mAccountView.setImageResource(R.drawable.ico_account);
			}
		}
	}

	/**
	 * Called after setContentView of activity override
	 */
	protected void initUIBase() {
		initUI();
		implementUI();
	}

	private void initUI() {
		mMenuView = (ImageView) findViewById(R.id.imv_menu);
		mAccountView = (ImageView) findViewById(R.id.imv_user);
		mTitle = (TextView) findViewById(R.id.title);
		initMenu(); // init slide menu
	}

	private void implementUI() {

		mMenuView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				mSlideMenu.toggle();
			}
		});

		mAccountView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (isLogin()) {
					/* account exist */
					LaunchIntent.start(BaseActivity.this,
							AccountInfoActivity.class);
				} else {

					/* login or register */
					mDialogAcc = new Dialog(BaseActivity.this);
					mDialogAcc.requestWindowFeature(Window.FEATURE_NO_TITLE);
					mDialogAcc.setContentView(R.layout.dialog_account);
					mDialogAcc.setCancelable(true);
					String title[] = {
							getResources().getString(R.string.dang_ki),
							getResources().getString(R.string.dang_nhap) };
					ListView listViewAcc = (ListView) mDialogAcc
							.findViewById(R.id.listView_acc);
					listViewAcc
							.setAdapter(new ArrayAdapter<String>(
									BaseActivity.this,
									R.layout.simple_list_item, title));
					mDialogAcc.show();

					listViewAcc
							.setOnItemClickListener(new OnItemClickListener() {

								@Override
								public void onItemClick(AdapterView<?> parent,
										View view, int position, long id) {
									switch (position) {
									case 0:
										// register
										LaunchIntent.start(BaseActivity.this,
												RegisterActivity.class);
										break;
									case 1:
										// login
										LaunchIntent.start(BaseActivity.this,
												LoginActivity.class);
										break;
									}
									mDialogAcc.dismiss();
								}
							});
				}
			}
		});
	}

	public void setRightMenuHeader(int resId,
			final View.OnClickListener listener) {
		mAccountView.setImageResource(R.drawable.icon_logout);
		mAccountView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (listener != null) {
					listener.onClick(v);
				}
			}
		});
	}

	/**
	 * Initialize all models not related view of activity
	 */
	protected void initModelBase(Bundle savedInstanceState) {

		if (mApplication == null) {
			mApplication = (MyApp) getApplication();
		}

		if (mContext == null) {
			mContext = getApplicationContext();
		}

		mFragmentManager = getSupportFragmentManager();
		mScrollingListener = new PauseOnScrollListener(UniversalImageUtil
				.getInstance(this).getImageLoader(), false, true);

	}

	/**
	 * Slide menu for all activity
	 */
	private void initMenu() {
		/* Menu iPhim */
		mMenuItems.add(MenuUIItem.build(getResources()
				.getString(R.string.iphim), R.drawable.ico_menu_iclip,
				new MenuUIItem.MenuItemListener() {

					@Override
					public void onClick() {

						if (BaseActivity.this instanceof IPhimActivity) {
							// iphim or iclip
							if (!((IPhimActivity) BaseActivity.this)
									.getHomeId().equals(AppConstants.ID_IPHIM)) {
								// iclip to iphim
								mSlideMenu.showContent(false);
								Bundle bundle = new Bundle();
								bundle.putString("home_id",
										AppConstants.ID_IPHIM);
								LaunchIntent.start(BaseActivity.this,
										IPhimActivity.class, bundle);
								return;
							}
						} else {
							mSlideMenu.showContent(false);
							Bundle bundle = new Bundle();
							bundle.putString("home_id", AppConstants.ID_IPHIM);
							LaunchIntent.start(BaseActivity.this,
									IPhimActivity.class, bundle);
							return;
						}
						mSlideMenu.showContent(true);
					}
				}));

		/* Menu iClip */
		mMenuItems.add(MenuUIItem.build(getResources()
				.getString(R.string.iclip), R.drawable.ico_menu_iclip,
				new MenuUIItem.MenuItemListener() {

					@Override
					public void onClick() {
						if (BaseActivity.this instanceof IPhimActivity) {
							// iphim or iclip
							if (!((IPhimActivity) BaseActivity.this)
									.getHomeId().equals(AppConstants.ID_ICLIP)) {
								// iphim to iclip
								mSlideMenu.showContent(false);
								Bundle bundle = new Bundle();
								bundle.putString("home_id",
										AppConstants.ID_ICLIP);
								LaunchIntent.start(BaseActivity.this,
										IPhimActivity.class, bundle);
								return;
							}
						} else {
							mSlideMenu.showContent(false);
							Bundle bundle = new Bundle();
							bundle.putString("home_id", AppConstants.ID_ICLIP);
							LaunchIntent.start(BaseActivity.this,
									IPhimActivity.class, bundle);
							return;
						}
						mSlideMenu.showContent(true);
					}
				}));

		/* Menu iNews */
		mMenuItems.add(MenuUIItem.build(getResources()
				.getString(R.string.inews), R.drawable.ico_menu_inews,
				new MenuUIItem.MenuItemListener() {

					@Override
					public void onClick() {
						boolean isActivityINews = BaseActivity.this instanceof ICategoryActivity
								&& ((ICategoryActivity) BaseActivity.this).mHomeId
										.equals(AppConstants.ID_INEWS);

						if (!isActivityINews) {
							mSlideMenu.showContent(false);
							Bundle bundle = new Bundle();
							bundle.putString("type", AppConstants.ID_INEWS);
							LaunchIntent.start(BaseActivity.this,
									ICategoryActivity.class, bundle);
							return;
						}
						mSlideMenu.showContent(true);
					}
				}));

		/* Menu iFun */
		mMenuItems.add(MenuUIItem.build(
				getResources().getString(R.string.ifun),
				R.drawable.ico_menu_ifun, new MenuUIItem.MenuItemListener() {

					@Override
					public void onClick() {
						boolean isActivityIFuns = BaseActivity.this instanceof ICategoryActivity
								&& ((ICategoryActivity) BaseActivity.this).mHomeId
										.equals(AppConstants.ID_IFUN);
						if (!isActivityIFuns) {
							mSlideMenu.showContent(false);
							Bundle bundle = new Bundle();
							bundle.putString("type", AppConstants.ID_IFUN);
							LaunchIntent.start(BaseActivity.this,
									ICategoryActivity.class, bundle);
							return;
						}
						mSlideMenu.showContent(true);
					}
				}));

		/* Menu share */
		mMenuItems.add(MenuUIItem.build(
				getResources().getString(R.string.share_app),
				R.drawable.ico_menu_share, new MenuUIItem.MenuItemListener() {

					@Override
					public void onClick() {
						mSlideMenu.showContent(false);
						AlertDialog.Builder builder = new AlertDialog.Builder(
								BaseActivity.this);
						// Add the buttons
						builder.setPositiveButton("Ok",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										mFacebook
												.requestUploadPhoto(
														AppConstants.LOGO,
														getString(R.string.share_app_message),
														new FacebookRequestStatus() {

															@Override
															public void startRequest() {
																showLoading(true);
															}

															@Override
															public void finishRequest(
																	Response response) {
																showLoading(false);
																if (response
																		.getError() == null) {
																	MyUtil.showDialog(
																			"Chia sẻ thành công",
																			BaseActivity.this);
																} else {
																	MyUtil.showDialog(
																			"Chia sẻ thất bại :(",
																			BaseActivity.this);
																	Log.e(response
																			.getError()
																			.toString());
																}
															}
														});
									}
								});
						builder.setNegativeButton("Cancel",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										if (mShareDialog != null) {
											mShareDialog.dismiss();
										}
									}
								});
						builder.setTitle("Thông báo");
						builder.setMessage("Bạn muốn chia sẻ iPhim qua facebook");
						mShareDialog = builder.create();
						mShareDialog.show();
						return;

					}
				}));

		/* Menu search */
		mMenuItems.add(MenuUIItem.build(
				getResources().getString(R.string.tim_kiem),
				R.drawable.ico_menu_search, new MenuUIItem.MenuItemListener() {

					@Override
					public void onClick() {
						if (!(BaseActivity.this instanceof SearchActivity)) {
							mSlideMenu.showContent(false);
							LaunchIntent.start(BaseActivity.this,
									SearchActivity.class);
							return;
						}
						mSlideMenu.showContent(true);
					}
				}));

		// configure the SlidingMenu
		mSlideMenu = new SlidingMenu(this);
		mSlideMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
		mSlideMenu.setShadowWidthRes(R.dimen.shadow_width);
		mSlideMenu.setShadowDrawable(R.drawable.shadow);
		mSlideMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		mSlideMenu.setFadeDegree(0.35f);
		mSlideMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
		mSlideMenu.setMenu(R.layout.menu_frame);
		mMenuFragment = MenuListFragment.newInstance(mMenuItems);
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.menu_frame, mMenuFragment).commit();
	}

	/**
	 * Set title of activity
	 * 
	 * @param title
	 */
	protected void setTitle(String title) {
		if (mTitle != null) {
			mTitle.setText(title);
		}
	}

	/**
	 * Show account button
	 * 
	 * @param show
	 */
	protected void showRightButton(boolean show) {
		mAccountView.setVisibility(show ? View.VISIBLE : View.INVISIBLE);
	}

	/**
	 * Show menu button
	 * 
	 * @param show
	 */
	protected void showLeftButton(boolean show) {
		mMenuView.setVisibility(show ? View.VISIBLE : View.INVISIBLE);
	}

	/**
	 * Remove previous show dialog fragment by tag
	 * 
	 * @param tag
	 *            tag of dialog fragment
	 */
	protected void removePreviousDialog(String tag) {
		// DialogFragment.show() will take care of adding the fragment
		// in a transaction. We also want to remove any currently showing
		// dialog, so make our own transaction and take care of that here.
		FragmentTransaction ft = mFragmentManager.beginTransaction();
		Fragment prev = mFragmentManager.findFragmentByTag(tag);
		if (prev != null) {
			ft.remove(prev);
		}
		ft.addToBackStack(null);
	}

	protected boolean isLogin() {
		User account = MyPreferenceManager.getInstance(this).getAccount();
		return (account != null);
	}

	/**
	 * Show view loading
	 * 
	 * @param isShow
	 */
	public void showLoading(boolean isShow) {
		if (mLoadingLayout == null) {
			ViewGroup root = (ViewGroup) this.getWindow().getDecorView()
					.findViewById(android.R.id.content);

			// create view for loading
			mLoadingLayout = LayoutInflater.from(this).inflate(
					R.layout.view_loading, null);
			root.addView(mLoadingLayout);
		}
		if (isShow) {
			mLoadingLayout.setVisibility(View.VISIBLE);
		} else if (mLoadingLayout != null) {
			mLoadingLayout.setVisibility(View.GONE);
		}
	}

	@Override
	public void finish() {
		super.finish();
		overridePendingTransition(R.anim.fade_in, R.anim.push_out);
	}

	public boolean isRunning() {
		return isRunning;
	}

	protected void shareItem(String name, String link, String description,
			String image) {
		if (TextUtils.isEmpty(link)) {
			link = "http://iphim.vn";
		}
		mFacebook.requestPostFeed(name, "", description, link, image,
				new FacebookRequestStatus() {

					@Override
					public void startRequest() {
						showLoading(true);
					}

					@Override
					public void finishRequest(Response response) {
						showLoading(false);
						if (response.getError() == null) {
							MyUtil.showDialog("Chia sẻ thành công",
									BaseActivity.this);
						} else {
							MyUtil.showDialog("Chia sẻ thất bại",
									BaseActivity.this);
							Log.e(response.getError().toString());
						}
					}
				});
	}
}